package com.healthysys.backend.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        // 设置响应头和状态码
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 构建返回的 JSON 数据
        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("message", "未登录，请先登录");

        // 使用 Jackson 序列化并写入响应体
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
        
        // 确保响应内容完整
        response.getWriter().flush();
    }
}